package com.my.internetplus.service;

import com.my.internetplus.dao.*;
import com.my.internetplus.model.Cart;
import com.my.internetplus.model.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class OrderService {

    @Resource
    private UserDao userDao;

    @Resource
    private OrderDao orderDao;

    @Resource
    private GoodDao goodDao;

    @Resource
    private AddressDao addressDao;

    @Resource
    private CartDao cartDao;
    public List<Order> getordersList(int userid){


        List<Order> orders = orderDao.getordersList(userid);
        for (Order order : orders) {
            System.out.println(order);

        }
        return orders;
    }

    public Map getOrderDetail(long orderid){
        Order selectorderbyid = orderDao.selectorderbyid(orderid);
        String selectgoodsid = orderDao.selectgoodsid(orderid);
        String[] goodid = selectgoodsid.split(",");
        HashMap<String,Object> map=new HashMap<>();
        map.put("order",selectorderbyid);
        List<String> goodsname=new ArrayList<String>();
        for (String s : goodid) {
           goodsname.add(goodDao.selectgoodnamebyid(Integer.parseInt(s)));
        }
        map.put("goodsname",goodsname);
        map.put("address",addressDao.selectAddressByOrderId(orderid));

        return map;
    }

    public void setCnform(long orderid){
        orderDao.setCnform(orderid);
    }
    public void delectOrder(long orderid){
        orderDao.delectOrder(orderid);
    }



    public void addorder(List cartid,int selectedAdd,String sum,String openid){


        List<Cart> carts = cartDao.selectCartByidList(cartid);
        //减少库存数量
        for (Cart cart : carts) {
            goodDao.subGoodAmountById(cart.getGoodId(),cart.getSum());
        }


        String goodid="";
        String orderid=String.valueOf(System.currentTimeMillis());
        orderDao.insertorder(orderid,sum,userDao.selectUserByOpenId(openid).getUserId());

        for (Cart cart : carts) {
            goodid+=cart.getGoodId()+",";
        }
        goodid=goodid.substring(0,goodid.length()-1);
        orderDao.insertorderdetail(orderid,goodid,selectedAdd);
          cartDao.deleteCart(cartid);

    }

}
